export function downloadFile(fileUrl: string, fileName: string) {
  let xhr = new XMLHttpRequest()
  xhr.open('GET', fileUrl, true)
  xhr.responseType = 'blob'
  xhr.onload = function () {
    let url = window.URL.createObjectURL(xhr.response)
    let a = document.createElement('a')
    a.href = url
    a.download = fileName
    a.click()
  }
  xhr.onerror = function () {
    window.open(`${fileUrl}?attname=${fileName}`, '_blank')
  }
  xhr.send()
}

export function jsonToParam(json: any) {
  if (!json) return ''
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return ''
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })
  ).join('&')
}

export function cleanArray(actual: any) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}

export function deepCopy<T extends object>(data:T):T {
  return JSON.parse(JSON.stringify(data))
}